package com.ths.inputservice.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.os.Build;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListPopupWindow;
import android.widget.PopupWindow;
import android.widget.Switch;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.SPUtils;
import com.ths.inputservice.R;
import com.ths.inputservice.adapter.RtspHistoryAdapter;
import com.ths.inputservice.utils.RtspHistoryManager;

import java.util.List;

public class SettingsPopupManager {

    private final Context context;
    private PopupWindow popupWindow;
    private EditText et1;
    private EditText et2;
    private Switch swSmall;
    private ListPopupWindow historyPopup1;
    private ListPopupWindow historyPopup2;

    public interface OnSettingsSavedListener {
        void onSettingsSaved(String url1, String url2);

        void onCheckedSwitch(Boolean b);

        void onCloseWindow(String url1, String url2);

        void onPopupOpened(); // ✅ 新增弹窗开启回调
    }

    private OnSettingsSavedListener listener;

    public SettingsPopupManager(Context context) {
        this.context = context;
    }

    public void setOnSettingsSavedListener(OnSettingsSavedListener listener) {
        this.listener = listener;
    }

    @SuppressLint("MissingInflatedId")
    public void showSettingsPopup(View anchorView) {
        // 停止播放视频
        if (context instanceof MainActivity) {
            ((MainActivity) context).pausePlayersForSettings();
        }

        // 创建弹窗视图
        View contentView = LayoutInflater.from(context).inflate(R.layout.popup_settings, null);

        // 初始化控件
        et1 = contentView.findViewById(R.id.et_rtsp1);
        et2 = contentView.findViewById(R.id.et_rtsp2);
        swSmall = contentView.findViewById(R.id.sw_small);
        ImageButton btnDropdown1 = contentView.findViewById(R.id.btn_dropdown1);
        ImageButton btnDropdown2 = contentView.findViewById(R.id.btn_dropdown2);
        Button btnSave = contentView.findViewById(R.id.btn_save);
        Button btnCancel = contentView.findViewById(R.id.btn_cancel);

        // 加载保存的URL
        SharedPreferences sp = context.getSharedPreferences("rtsp", Context.MODE_PRIVATE);
        et1.setText(sp.getString("url1", "rtsp://192.168.144.25:8554/main.264"));
        et2.setText(sp.getString("url2", "rtsp://192.168.144.26:8554/main.264"));

        // 设置下拉按钮点击事件
        btnDropdown1.setOnClickListener(v -> showHistoryPopup(1, et1, v));
        btnDropdown2.setOnClickListener(v -> showHistoryPopup(2, et2, v));

        // 设置开关状态
        boolean showWindow = SPUtils.getInstance().getBoolean("ShowWindow", true);
        swSmall.setChecked(showWindow);
        swSmall.setOnCheckedChangeListener((@NonNull CompoundButton compoundButton, boolean b) -> {
            if (listener != null) {
                listener.onCheckedSwitch(b);
                SPUtils.getInstance().put("ShowWindow", b);
            }
        });

        // 设置保存按钮
        btnSave.setOnClickListener(v -> {
            String url1 = et1.getText().toString().trim();
            String url2 = et2.getText().toString().trim();

            // 保存到SharedPreferences
            sp.edit().putString("url1", url1)
                    .putString("url2", url2)
                    .apply();

            // 保存到历史记录
            if (!url1.isEmpty() && !"关闭".equals(url1)) {
                RtspHistoryManager.addToHistory(context, 1, url1);
            }
            if (!url2.isEmpty() && !"关闭".equals(url2)) {
                RtspHistoryManager.addToHistory(context, 2, url2);
            }

            // 回调保存事件
            if (listener != null) {
                listener.onSettingsSaved(url1, url2);
            }

            // 关闭弹窗
            dismissPopup();
        });

        // 取消按钮关闭弹窗
        btnCancel.setOnClickListener(v -> dismissPopup());

        // 计算弹窗大小
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Point size = new Point();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            context.getDisplay().getRealSize(size);
        } else {
            wm.getDefaultDisplay().getRealSize(size);
        }

        int orientation = context.getResources().getConfiguration().orientation;
        int width, height;

        if (orientation == android.content.res.Configuration.ORIENTATION_LANDSCAPE) {
            width = size.x / 2;
            height = WindowManager.LayoutParams.MATCH_PARENT;
        } else {
            width = WindowManager.LayoutParams.MATCH_PARENT;
            height = size.y / 2;
        }

        // 创建并显示弹窗
        popupWindow = new PopupWindow(contentView, width, height, true);
        popupWindow.setAnimationStyle(android.R.style.Animation_Dialog);
        popupWindow.setBackgroundDrawable(null);

        // ✅ 弹窗显示监听
        if (listener != null) listener.onPopupOpened();

        // ✅ 弹窗关闭监听
        popupWindow.setOnDismissListener(() -> {
            if (listener != null) {
                String url1 = et1.getText().toString().trim();
                String url2 = et2.getText().toString().trim();

                if (!url1.isEmpty() && !"关闭".equals(url1)) {
                    RtspHistoryManager.addToHistory(context, 1, url1);
                }
                if (!url2.isEmpty() && !"关闭".equals(url2)) {
                    RtspHistoryManager.addToHistory(context, 2, url2);
                }

                listener.onCloseWindow(url1, url2);
            }

            if (historyPopup1 != null && historyPopup1.isShowing()) historyPopup1.dismiss();
            if (historyPopup2 != null && historyPopup2.isShowing()) historyPopup2.dismiss();
        });

        // 设置弹窗位置
        if (orientation == android.content.res.Configuration.ORIENTATION_LANDSCAPE) {
            popupWindow.showAtLocation(anchorView, Gravity.END | Gravity.CENTER_VERTICAL, 0, 0);
        } else {
            popupWindow.showAtLocation(anchorView, Gravity.BOTTOM, 0, 0);
        }
    }

    private void showHistoryPopup(int channelId, EditText targetEditText, View anchor) {
        List<String> historyList = RtspHistoryManager.getHistory(context, channelId);
        RtspHistoryAdapter adapter = new RtspHistoryAdapter(context, historyList);

        ListPopupWindow popupWindow = new ListPopupWindow(context);
        popupWindow.setAdapter(adapter);
        popupWindow.setAnchorView(anchor);
        popupWindow.setWidth(targetEditText.getWidth() + anchor.getWidth());
        popupWindow.setModal(true);

        popupWindow.setOnItemClickListener((parent, view, position, id) -> {
            if (position < historyList.size()) {
                targetEditText.setText(historyList.get(position));
            } else {
                targetEditText.setText("关闭");
            }
            popupWindow.dismiss();
        });

        popupWindow.show();

        if (channelId == 1) {
            if (historyPopup2 != null && historyPopup2.isShowing()) {
                historyPopup2.dismiss();
            }
            historyPopup1 = popupWindow;
        } else {
            if (historyPopup1 != null && historyPopup1.isShowing()) {
                historyPopup1.dismiss();
            }
            historyPopup2 = popupWindow;
        }
    }

    public void dismissPopup() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
        if (historyPopup1 != null && historyPopup1.isShowing()) historyPopup1.dismiss();
        if (historyPopup2 != null && historyPopup2.isShowing()) historyPopup2.dismiss();
    }
}
